package com.erp.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.user.domain.ErpDistributionUser;
import com.erp.user.domain.bo.ErpDistributionUserBo;
import com.erp.user.domain.vo.CityVo;
import com.erp.user.domain.vo.ErpDistributionUserVo;
import com.erp.user.mapper.ErpDistributionUserBasicInfoMapper;
import com.erp.user.mapper.ErpDistributionUserMapper;
import com.erp.user.service.ICityService;
import com.erp.user.service.IErpDistributionUserBasicInfoService;
import com.erp.user.service.IErpDistributionUserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.uuid.RandomUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Description: 分销员开户信息Service业务层处理
 * @Author: j.zh
 * @Date: 2024/5/2
 * @Version: 4.0.0
**/
@RequiredArgsConstructor
@Service
public class ErpDistributionUserServiceImpl implements IErpDistributionUserService {

	@Resource
	ErpDistributionUserMapper baseMapper;
	@Resource
	ICityService cityService;
	@Resource
	IErpDistributionUserBasicInfoService distributionUserBasicInfoService;

	/**
	 * @Description: 根据主键获取分销员信息
	 * @Author: j.zh
	 * @Date: 2024/5/2
	 * @param distributionUserId
	 * @return com.erp.user.domain.ErpDistributionUser
	 * @Version: 4.0.0
	**/
	@Override
	public ErpDistributionUser getDistributionUserById(Long distributionUserId) {
		return baseMapper.selectById(distributionUserId);
	}

	/**
	 * @Description: 根据UserId获取分销员信息
	 * @Author: j.zh
	 * @Date: 2024/6/25
	 * @param userId
	 * @return
	 * @Version: 4.2.0
	 **/
	@Override
	public ErpDistributionUser getByUserId(Long userId){
		return baseMapper.selectOne(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getUserId, userId));
	}

	/**
	 * @Description: 新增分销员
	 * @Author: j.zh
	 * @Date: 2024/5/2
	 * @param distributionUser
	 * @return java.lang.Long 主键
	 * @Version: 4.0.0
	 **/
	@Override
	public Long insertDistributionUser(ErpDistributionUser distributionUser){
		baseMapper.insert(distributionUser);
		return distributionUser.getDistributionUserId();
	}

	/**
	 * @Description: 查询开户信息列表
	 * @Author: j.zh
	 * @Date: 2024/5/2
	 * @param bo
	 * @param pageQuery
	 * @return com.ruoyi.common.core.web.oldPage.TableDataInfo<com.erp.user.domain.vo.ErpDistributionUserVo>
	 * @Version: 4.0.0
	**/
	@Override
	public TableDataInfo<ErpDistributionUserVo> queryPageList(ErpDistributionUserBo bo, PageQuery pageQuery) {
		Page<ErpDistributionUserVo> result = baseMapper.selectVoPageByUser(pageQuery.build(), bo);
		List<ErpDistributionUserVo> records = result.getRecords();
		records.forEach(vo -> {
			Long userId = vo.getUserId();
			String manageCity = vo.getManageCity();
			String cityName = "";
			// 获取经营城市
			if (manageCity != null) {
				String replaceAll = manageCity.replaceAll("\\[", "").replaceAll("]", "");
				List<String> collect = Arrays.stream(replaceAll.split(",")).collect(Collectors.toList());
				for (int i = 0; i < collect.size(); i++) {
					if ((i+1) % 2 == 0) {
						String s = collect.get(i);
						Integer cityId = Integer.parseInt(s);
						CityVo cityVo = cityService.queryById(cityId);
						cityName = cityName + "," + cityVo.getCity();
					}
				}
			}
			vo.setManageCity(cityName.replaceFirst(",", ""));
			// 获取分公司名称
			if((bo.getType() == 2 || bo.getType() == 3) && vo.getParentBranchId() != null){
				if (vo.getParentBranchId() == 1){
					vo.setParentBranchName("总公司");
				}else {
					vo.setParentBranchName(distributionUserBasicInfoService.getByDistributionUserId(vo.getParentBranchId()).getCorporateName());
				}
			}
			// 获取代理名称
			if(bo.getType() == 3  && vo.getParentAgentId() != null){
				vo.setParentAgentName(distributionUserBasicInfoService.getByDistributionUserId(vo.getParentAgentId()).getRealName());
			}
		});
		result.setRecords(records);
		return TableDataInfo.build(result);
	}

	/**
	 * @Description: 生成六位数的邀请码
	 * @Author: j.zh
	 * @Date: 2024/5/2
	 * @return java.lang.String
	 * @Version: 4.0.0
	 **/
	@Override
	public String createInvitationCode(){
		while (true){
			// 生成邀请码
			String invitationCode = RandomUtils.generateRandomNumber(6);
			// 根据邀请码进行查重
			ErpDistributionUser distributionUser = baseMapper.selectOne(new LambdaQueryWrapper<ErpDistributionUser>()
					.eq(ErpDistributionUser::getInvitationCode, invitationCode));
			if (distributionUser == null){
				return invitationCode;
			}
		}
	}

	/**
	 * @Description: 生成身份代码
	 * @Author: j.zh
	 * @Date: 2024/5/2
	 * @param codeType
	 * @return java.lang.String
	 * @Version: 4.0.0
	 **/
	@Override
	public String createIdentityCode(Integer codeType){
		String identityCode = "";
		while (true){
			switch (codeType){
				case 1:
					identityCode = "G" + RandomUtils.generateRandomNumber(3);
					break;
				case 2:
					// 代理
					identityCode = "D" + RandomUtils.generateRandomNumber(4);
					break;
				case 3:
					// 个人
					identityCode = RandomUtils.generateRandomNumber(8);
					break;
				default:
					identityCode = RandomUtils.generateRandomNumber(10);
			}
			// 查重
			ErpDistributionUser distributionUser = baseMapper.selectOne(new LambdaQueryWrapper<ErpDistributionUser>()
					.eq(ErpDistributionUser::getIdentityCode, identityCode).eq(ErpDistributionUser::getType, codeType));
			if (distributionUser == null){
				break;
			}
		}

		return identityCode;
	}

	@Override
	public List<ErpDistributionUserVo> queryPageBranchAndAgent() {
		List<ErpDistributionUserVo> branchOfficeInfos = baseMapper.selectVoList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getType, 1));
		branchOfficeInfos.forEach(vo -> {
			Long id = vo.getDistributionUserId();
			List<ErpDistributionUserVo> agentInfos = baseMapper
					.selectVoList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getParentBranchId, id).eq(ErpDistributionUser::getType, 2));
			vo.setChildAgentList(agentInfos);
		});
		return branchOfficeInfos;
	}

	@Override
	public List<ErpDistributionUserVo> queryPageBranchAndAgentUser() {
		List<ErpDistributionUserVo> branchOfficeInfos = baseMapper.selectVoList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getType, 1));
		branchOfficeInfos.forEach(vo -> {
			Long branchId = vo.getDistributionUserId();
			List<ErpDistributionUserVo> agentInfos = baseMapper
					.selectVoList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getParentBranchId, branchId)
							.eq(ErpDistributionUser::getType, 2));
			if (agentInfos.size() != 0) {
				for (ErpDistributionUserVo agentInfo : agentInfos) {
					Long agentId = agentInfo.getDistributionUserId();
					List<ErpDistributionUserVo> infoVos = baseMapper
							.selectVoList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getParentAgentId, agentId)
									.eq(ErpDistributionUser::getType, 3));
					agentInfo.setChildUserList(infoVos);
				}
			}
			vo.setChildAgentList(agentInfos);
		});
		return branchOfficeInfos;
	}

	/**
	 * @Description: 获取用户ERP有效期
	 * @Author: j.zh
	 * @Date: 2024/5/3
	 * @param userId
	 * @return java.lang.String
	 * @Version: 4.0.0
	**/
	@Override
    public String getUserExpirationTime(Long userId) {
        ErpDistributionUser distributionUser = baseMapper.selectOne(new LambdaQueryWrapper<ErpDistributionUser>()
				.eq(ErpDistributionUser::getUserId, userId));
        if (distributionUser != null) {
            Date expirationTime = distributionUser.getExpirationTime();
            //获取当前时间时间戳
            Long nowTime =  new Date().getTime();
            if (nowTime - expirationTime.getTime() > 0){
                //已过期
                return "已过有效期";
            }else {
                //未过期
                return expirationTime.toString();
            }
        } else {
            return "暂无有效期";
        }
    }

	/**
	 * @Description: 根据分销员ID和类型，查询其下级分销员列表
	 * @Author: j.zh
	 * @Date: 2024/5/4
	 * @param distributionUserId
	 * @param type
	 * @return java.util.List<com.erp.user.domain.ErpDistributionUser>
	 * @Version: 4.0.0
	 **/
	@Override
	public List<ErpDistributionUser> getListByIdAndType(Long distributionUserId, Integer type){
		if (type == 1){
			// 分公司，则查询代理列表
			if(distributionUserId.intValue() == 1){
				// 总公司所有代理
				return baseMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
						.eq(ErpDistributionUser::getType, 2)
						.and(wrapper -> wrapper.isNull(ErpDistributionUser::getParentBranchId).or().eq(ErpDistributionUser::getParentBranchId, distributionUserId)));
			}else {
				return baseMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
						.eq(ErpDistributionUser::getType, 2).eq(ErpDistributionUser::getParentBranchId, distributionUserId));
			}
		}else if (type == 2){
			// 代理，则查询个人列表
			if(distributionUserId.intValue() == 1){
				// 总公司所有个人
				return baseMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
						.eq(ErpDistributionUser::getType, 3)
						.and(wrapper -> wrapper.isNull(ErpDistributionUser::getParentBranchId).or().eq(ErpDistributionUser::getParentBranchId, distributionUserId)));
			}else {
				return baseMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
						.eq(ErpDistributionUser::getType, 3).eq(ErpDistributionUser::getParentAgentId, distributionUserId));
			}
		}else {
			return null;
		}
	}

	/**
	 * @Description: 根据类型查询分销成员列表 1-分公司 2-代理 3-ERP 其他-全部
	 * @Author: j.zh
	 * @Date: 2024/7/4
	 * @param type
	 * @return
	 * @Version: 4.2.0
	 **/
	@Override
	public List<ErpDistributionUser> getListByDistributionUserType(Integer type){
		if (type.intValue() > 3 || type.intValue() < 1){
			return baseMapper.selectList();
		}
		return baseMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>().eq(ErpDistributionUser::getType, type)
				.or().eq(ErpDistributionUser::getDistributionUserId, 1l).orderByAsc(ErpDistributionUser::getDistributionUserId));
	}
}
